using UnityEngine;

public class PatrolState : IState
{
    private int patrolPosition;    // 当前巡逻点索引

    public PatrolState(FSM manager)
    {
        this.manager = manager;
        this.parameter = manager.parameter;
    }

    public override void OnEnter()
    {
        parameter.animator.Play("Walk");
    }

    public override void OnUpdate()
    {
        // 如果被击中了，转换到受击状态
        if (parameter.getHit)
        {
            manager.TransitionState(StateType.Hit);
        }

        // 如果有目标且目标在追逐范围内，则转换到反应状态
        if (parameter.target != null &&
            parameter.target.position.x >= parameter.chasePoints[0].position.x &&
            parameter.target.position.x <= parameter.chasePoints[1].position.x)
        {
            manager.TransitionState(StateType.React);
        }

        // 如果已经接近当前巡逻点，则转换到空闲状态
        if (Vector2.Distance(manager.transform.position, parameter.patrolPoints[patrolPosition].position) < .1f)
        {
            manager.TransitionState(StateType.Idle);
        }
    }
    
    public override void OnFixedUpdate()
    {
        // 朝向当前巡逻点
        manager.FlipTo(parameter.patrolPoints[patrolPosition]);
        
        // 移动到当前巡逻点
        manager.transform.position = Vector2.MoveTowards(manager.transform.position,
            parameter.patrolPoints[patrolPosition].position, parameter.moveSpeed * Time.deltaTime);
    }

    public override void OnExit()
    {
        patrolPosition++;    // 切换到下一个巡逻点

        // 如果超过巡逻点数组长度，循环回到第一个巡逻点
        if (patrolPosition >= parameter.patrolPoints.Length)
        {
            patrolPosition = 0;
        }
    }
}
